package cuit.campus.taskRunning.deliver.controller;

import cuit.campus.taskRunning.commons.response.Result;
import cuit.campus.taskRunning.deliver.entry.Deliver;
import cuit.campus.taskRunning.deliver.entry.vo.DeliverVo;
import cuit.campus.taskRunning.deliver.service.DeliverService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/runner")
public class DeliverController {
    @Autowired
    private final DeliverService service;
    // 注入密码加密器，建议在配置类中定义为Bean
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    // 构造函数注入服务
    public DeliverController(DeliverService service) {
        this.service = service;
    }

    @PostMapping("/register")
    Result register(@RequestBody DeliverVo deliver) {
        // 1. 验证输入的密码是否存在
        if (deliver.getRunner_password() == null || deliver.getRunner_password().trim().isEmpty()) {
            return Result.fail("密码不能为空");
        }

        // 2. 创建实体对象并复制属性
        Deliver d = new Deliver();
        BeanUtils.copyProperties(deliver, d);

        // 3. 对密码进行加盐哈希处理（BCrypt会自动生成随机盐值）
        String encodedPassword = passwordEncoder.encode(deliver.getRunner_password());
        d.setRunnerPassword(encodedPassword); // 保存加密后的密码

        // 4. 保存用户信息
        boolean flag = service.saveDeliver(d);

        if (flag) {
            return Result.ok("注册成功");
        } else {
            return Result.fail("注册失败");
        }
    }

    @PostMapping("/login")
    Result login(@RequestBody DeliverVo deliver){
        return service.login(deliver.getRunner_account(),deliver.getRunner_password());

    }
}
